import { assign, forEach, isArray } from "min-dash";

import { is } from "bpmn-js/lib/util/ModelUtil";

import { isExpanded, isEventSubProcess } from "bpmn-js/lib/util/DiUtil";

import { isAny } from "bpmn-js/lib/features/modeling/util/ModelingUtil";

import { getChildLanes } from "bpmn-js/lib/features/modeling/util/LaneUtil";

import { hasPrimaryModifier } from "diagram-js/lib/util/Mouse";

/**
 * A provider for BPMN 2.0 elements context pad
 */
export default function ContextPadProvider(
  config,
  injector,
  eventBus,
  contextPad,
  modeling,
  elementFactory,
  connect,
  create,
  popupMenu,
  canvas,
  rules,
  translate,
  elementRegistry
) {
  config = config || {};

  contextPad.registerProvider(this);  // 定义这是一个contextPad

  this._contextPad = contextPad;

  this._modeling = modeling;

  this._elementFactory = elementFactory;
  this._connect = connect;
  this._create = create;
  this._popupMenu = popupMenu;
  this._canvas = canvas;
  this._rules = rules;
  this._translate = translate;

  if (config.autoPlace !== false) {
    this._autoPlace = injector.get("autoPlace", false);
  }

  eventBus.on("create.end", 250, function(event) {
    var context = event.context,
      shape = context.shape;

    if (!hasPrimaryModifier(event) || !contextPad.isOpen(shape)) {
      return;
    }

    var entries = contextPad.getEntries(shape);

    if (entries.replace) {
      entries.replace.action.click(event, shape);
    }
  });
}

ContextPadProvider.$inject = [
  "config.contextPad",
  "injector",
  "eventBus",
  "contextPad",
  "modeling",
  "elementFactory",
  "connect",
  "create",
  "popupMenu",
  "canvas",
  "rules",
  "translate",
  "elementRegistry"
];

/**
 * getContextPadEntries为固定方法
 */
ContextPadProvider.prototype.getContextPadEntries = function(element) {
  var contextPad = this._contextPad
  var modeling = this._modeling
  var elementFactory = this._elementFactory
  var connect = this._connect
  var create = this._create
  var popupMenu = this._popupMenu
  var canvas = this._canvas
  var rules = this._rules
  var autoPlace = this._autoPlace
  var translate = this._translate

  var actions = {}

  if (element.type === "label") {
    return actions
  }

  var businessObject = element.businessObject

  function startConnect(event, element) {
    connect.start(event, element)
  }

  function removeElement() {
    modeling.removeElements([element]);
  }

  function getReplaceMenuPosition(element) {
    var Y_OFFSET = 5

    var diagramContainer = canvas.getContainer()
    var pad = contextPad.getPad(element).html

    var diagramRect = diagramContainer.getBoundingClientRect()
    var padRect = pad.getBoundingClientRect()

    var top = padRect.top - diagramRect.top
    var left = padRect.left - diagramRect.left

    var pos = {
      x: left,
      y: top + padRect.height + Y_OFFSET
    }

    return pos
  }

  /**
   * Create an append action
   *
   * @param {string} type
   * @param {string} className
   * @param {string} [title]
   * @param {Object} [options]
   *
   * @return {Object} descriptor
   */
  function appendAction(type, className, title, options) {
    if (typeof title !== "string") {
      options = title
      title = translate("Append {type}", { type: type.replace(/^bpmn:/, "") })
    }

    function appendStart(event, element) {
      var shape = elementFactory.createShape(assign({ type: type }, options))
      create.start(event, shape, {
        source: element
      })
    }

    var append = autoPlace
      ? function(event, element) {
          var shape = elementFactory.createShape(assign({ type: type }, options));

          autoPlace.append(element, shape);
        }
      : appendStart;

    return {
      group: "model", //  属于哪个分组, 比如tools、event、gateway、activity等等,用于分类
      className: className, //  样式类名, 我们可以通过它给元素修改样式
      title: title, //  鼠标移动到元素上面给出的提示信息
      action: { //  用户操作时会触发的事件
        dragstart: appendStart,
        click: append
      }
    };
  }

  function splitLaneHandler(count) {
    return function(event, element) {
      modeling.splitLane(element, count);

      contextPad.open(element, true);
    };
  }

  if (is(businessObject, "bpmn:FlowNode")) {
    //  网关
    if (is(businessObject, "bpmn:EventBasedGateway")) {
      assign(actions, {
        "append.receive-task": appendAction("bpmn:ReceiveTask", "bpmn-icon-receive-task", translate("Append ReceiveTask")),
        "append.message-intermediate-event": appendAction( "bpmn:IntermediateCatchEvent", "bpmn-icon-intermediate-event-catch-message", translate("Append MessageIntermediateCatchEvent"), { eventDefinitionType: "bpmn:MessageEventDefinition" } ),
        "append.timer-intermediate-event": appendAction( "bpmn:IntermediateCatchEvent", "bpmn-icon-intermediate-event-catch-timer", translate("Append TimerIntermediateCatchEvent"), { eventDefinitionType: "bpmn:TimerEventDefinition" } ),
        "append.condition-intermediate-event": appendAction( "bpmn:IntermediateCatchEvent", "bpmn-icon-intermediate-event-catch-condition", translate("Append ConditionIntermediateCatchEvent"), { eventDefinitionType: "bpmn:ConditionalEventDefinition" } ),
        "append.signal-intermediate-event": appendAction( "bpmn:IntermediateCatchEvent", "bpmn-icon-intermediate-event-catch-signal", translate("Append SignalIntermediateCatchEvent"), { eventDefinitionType: "bpmn:SignalEventDefinition" } )
      });
    }
    //  边界事件和补偿事件
    else if (isEventType(businessObject, "bpmn:BoundaryEvent", "bpmn:CompensateEventDefinition")) {
      assign(actions, {
        "append.compensation-activity": appendAction("bpmn:Task", "bpmn-icon-task", translate("Append compensation activity"), {
          isForCompensation: true
        })
      });
    }
    //  结束事件
    else if (
      !is(businessObject, "bpmn:EndEvent") &&
      //  不是补偿活动
      !businessObject.isForCompensation &&
      //  bpmn:IntermediateThrowEvent是一种中间事件，中间事件通常表示为一个带有双圆圈边框的圆形图标，内部包含一个标志，标志的类型取决于事件的类型（如信号、消息、错误等）
      //  LinkEventDefinition 是定义了链接事件的行为和属性
      !isEventType(businessObject, "bpmn:IntermediateThrowEvent", "bpmn:LinkEventDefinition") &&
      !isEventSubProcess(businessObject)
    ) {
      assign(actions, {
        //  追加结束事件
        "append.end-event": appendAction("bpmn:EndEvent", "bpmn-icon-end-event-none", translate("Append EndEvent")),
        //  追加网关
        "append.gateway": appendAction("bpmn:ExclusiveGateway", "bpmn-icon-gateway-none", translate("Append Gateway")),
        //  追加任务
        "append.append-task": appendAction("bpmn:UserTask", "bpmn-icon-user-task", translate("Append Task")),
        //  追加中间抛出事件/边界事件
        "append.intermediate-event": appendAction( "bpmn:IntermediateThrowEvent", "bpmn-icon-intermediate-event-none", translate("Append Intermediate/Boundary Event") )
      });
    }
  }

  //  使用顺序/消息流或者关联连接
  if (isAny(businessObject, ["bpmn:FlowNode", "bpmn:InteractionNode", "bpmn:DataObjectReference", "bpmn:DataStoreReference"])) {
    assign(actions, {"append.text-annotation": appendAction("bpmn:TextAnnotation", "bpmn-icon-text-annotation"),

      connect: {
        group: "connect",
        className: "bpmn-icon-connection-multi",
        title: translate("Connect using " + (businessObject.isForCompensation ? "" : "Sequence/MessageFlow or ") + "Association"),
        action: {
          click: startConnect,
          dragstart: startConnect
        }
      }
    });
  }

  //  使用数据输入关联连接
  if (isAny(businessObject, ["bpmn:DataObjectReference", "bpmn:DataStoreReference"])) {
    assign(actions, {
      connect: {
        group: "connect",
        className: "bpmn-icon-connection-multi",
        title: translate("Connect using DataInputAssociation"),
        action: {
          click: startConnect,
          dragstart: startConnect
        }
      }
    });
  }

  if (is(businessObject, "bpmn:Group")) {
    assign(actions, {
      "append.text-annotation": appendAction("bpmn:TextAnnotation", "bpmn-icon-text-annotation")
    });
  }

  // delete element entry, only show if allowed by rules
  var deleteAllowed = rules.allowed("elements.delete", { elements: [element] });

  if (isArray(deleteAllowed)) {
    // was the element returned as a deletion candidate?
    deleteAllowed = deleteAllowed[0] === element;
  }

  if (deleteAllowed) {
    assign(actions, {
      delete: {
        group: "edit",
        className: "bpmn-icon-trash",
        title: translate("Remove"),
        action: {
          click: removeElement
        }
      }
    });
  }

  return actions;
};

function isEventType(eventBo, type, definition) {
  var isType = eventBo.$instanceOf(type);
  var isDefinition = false;

  var definitions = eventBo.eventDefinitions || [];
  forEach(definitions, function(def) {
    if (def.$type === definition) {
      isDefinition = true;
    }
  });

  return isType && isDefinition;
}
